/*
 * @Author: 黄威
 * @Date: 2023-03-09 15:04:26
 * @LastEditors: 黄威
 * @LastEditTime: 2024-04-28 13:32:30
 * @Description: 可拖动的 card
 */

import React, { useEffect, useRef, useState } from 'react';
import ReactDOM from 'react-dom';

import Draggable from 'react-draggable';
import { Button, Card } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { useMemoizedFn } from 'ahooks';

interface DraggableCardProps {
  title: any;
  children: any;
  open?: boolean;
  closeAble?: boolean;
  onClose?: () => void;
  destroyOnClose?: boolean;
  className?: string;
  style?: React.CSSProperties;
  bounds?: string;
}

function DraggableCard(props: DraggableCardProps) {
  const {
    title,
    children,
    open,
    closeAble = true,
    onClose,
    destroyOnClose = false,
    className = '',
    style,
    bounds = 'parent',
  } = props;

  const [isInit, setIsInit] = useState(open);
  const ref = useRef<any>();

  const setRef = useMemoizedFn((e?: Event) => {
    e && e.stopPropagation();

    const nodes = document.querySelectorAll('.draggable-card-mask');

    nodes.forEach((node: any) => {
      node.style.zIndex = node === ref.current ? '1000' : '999';
    });
  });

  useEffect(() => {
    if (open) {
      setIsInit(true);
      setRef();
    }
  }, [open, setRef]);

  return ReactDOM.createPortal(
    <div
      ref={ref}
      className="draggable-card-mask fixed inset-0 pointer-events-none"
      style={open ? {} : { display: 'none' }}
    >
      <Draggable x-if={isInit} handle=".ant-card-head-title" cancel=".fixed" bounds={bounds} onMouseDown={setRef}>
        <Card
          title={title}
          extra={
            <Button
              x-if={closeAble}
              type="text"
              size="small"
              icon={<CloseOutlined />}
              onClick={() => onClose && onClose()}
            />
          }
          className={`flex-card draggable-card pointer-events-auto ${className}`}
          style={style}
        >
          <div x-if={destroyOnClose}>{open && children}</div>
          <div x-else style={open ? {} : { display: 'none' }}>
            {children}
          </div>
        </Card>
      </Draggable>
    </div>,
    document.body,
  );
}

export default DraggableCard;
